package com.blast.manager.delay.adapter

import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.View
import androidx.appcompat.widget.AppCompatAutoCompleteTextView
import androidx.appcompat.widget.AppCompatTextView
import com.blast.manager.R
import com.chad.library.adapter.base.BaseViewHolder
import com.wxl.common.adapter.AbsKeyEventMultilAdapter
import com.wxl.common.room.entity.LeiGuanEntity
import com.wxl.common.room.helper.DBHelper
import com.wxl.common.util.*
import com.wxl.common.wiget.SkinKeyEventEditorText

class DelayAdapter : AbsKeyEventMultilAdapter<LeiGuanEntity> {

    private var isEditor = false
    private var mOnEditorCallback: OnEditorCallback? = null
    val ets = ArrayList<AppCompatAutoCompleteTextView>()
    val texts = ArrayList<AppCompatTextView>()
    val widths = ArrayList<Int>()

    constructor(data: List<LeiGuanEntity>?) : super(data) {
        addItemType(0, R.layout.item_delay_list_layout)
        addItemType(1, R.layout.item_insert_delay)
        addItemType(2, R.layout.item_update_delay)
        pageSize = 10
        position = 0
    }

    fun setOnEditorCallback(mOnEditorCallback: OnEditorCallback) {
        this.mOnEditorCallback = mOnEditorCallback
    }

    fun setWidths(widths: ArrayList<Int>) {
        this.widths.clear()
        this.widths.addAll(widths)
    }

    override fun getItemViewType(position: Int): Int {
        return data[position].editor
    }

    override fun convert(helper: BaseViewHolder, item: LeiGuanEntity) {
        super.convert(helper, item)

        if (helper.itemViewType == 0) {
            if (this.widths.isNotEmpty()) {
                setViewWidth(
                    helper.getView(R.id.itemDelayNumberText)
                    , helper.getView(R.id.itemDelayCodeText)
                    , helper.getView(R.id.itemDelayTimeText)
                    , helper.getView(R.id.itemDelaySortText)
                    , helper.getView(R.id.itemDelayKongText)
                    , helper.getView(R.id.itemDelayCjqText)
                )
            }
            item.run {
                helper.setText(R.id.itemDelayNumberText, (helper.adapterPosition + 1).toString())
                helper.setText(R.id.itemDelayCodeText, StringUtils.getUid(UID))
                helper.setText(R.id.itemDelayTimeText, delay)
                if (!TextUtils.isEmpty(holeNumber)) {
                    val hexString: String = StringUtils.HexToBin16(holeNumber)
                    helper.setText(
                        R.id.itemDelaySortText,
                        StringUtils.getRowNumber(hexString).toString()
                    )
                    helper.setText(
                        R.id.itemDelayKongText,
                        StringUtils.getHoleNumber(hexString).toString()
                    )
                    helper.setText(R.id.itemDelayCjqText, collectorNumber)
                } else {
                    helper.setText(R.id.itemDelaySortText, "")
                    helper.setText(R.id.itemDelayKongText, "")
                    helper.setText(R.id.itemDelayCjqText, "")
                }
            }
        } else if (helper.itemViewType == 1) {
            convertInsertDelay(helper, item)
        } else if (helper.itemViewType == 2) {
            convertUpdateDelay(helper, item)
        }
    }


    private fun setViewWidth(vararg vs: View) {
        (0 until vs.size).forEach { i ->
            vs[i].layoutParams.width = widths[i]
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (isEditor) {
            if (keyCode == KeyEvent.KEYCODE_ENTER) {
                checkDataTotalDelay()
            }
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                removeEditorItemState()
                return true
            }
            return false
        }
        return super.onKeyDown(keyCode, event)
    }

    /**
     * 移除正在编辑的Item状态
     */
    private fun removeEditorItemState() {
        if (position >= 0 && isEditor) {
            if (data[position].editor == 1) {
                isEditor = false
                data.removeAt(position)
                notifyItemRemoved(position)
            } else if (data[position].editor == 2) {
                isEditor = false
                data[position].editor = 0
                notifyItemChanged(position)
            }
        } else if (isEditor) {//防止意外
            data.forEach {
                if (it.editor == 1) {
                    isEditor = false
                    data.remove(it)
                } else if (it.editor == 2) {
                    isEditor = false
                    it.editor = 0
                }
            }
            notifyDataSetChanged()
        }
        mOnEditorCallback?.onEditorResult()
    }


    /**
     * 绑定编辑好的数据到item
     */
    private fun bindEditorData(item: LeiGuanEntity): Boolean {
        if (ets.isNotEmpty()) {
            if (ets.size >= 4) {//插入
                if (!TextUtils.isEmpty(ets[0].text)) {
                    val uid2 = SerialUtil.getUid2(ets[0].text.toString())
                    if (checkUidRepeat(uid2)) {
                        return false
                    }
                    item.UID = uid2
                }
                if (!TextUtils.isEmpty(ets[1].text)) {
                    item.delay = ets[1].text.toString()
                }
                if (!TextUtils.isEmpty(ets[2].text)) {
                    item.sort = ets[2].text.toString()
                }
                if (!TextUtils.isEmpty(ets[3].text)) {
                    item.kong = ets[3].text.toString()
                }

            } else {
                item.delay = ets[0].text.toString()
            }
        }
        return true
    }


    /**
     * 检查修改之后的延时时间是否超过12s
     */
    private fun checkDataTotalDelay() {
        val item = getItem(position)

        if (ets.size >= 4) {
            if (TextUtils.isEmpty(ets[1].text.toString())) {
                item!!.delay = "0"
            } else {
                item!!.delay = ets[1].text.toString()
            }
        } else {
            if (TextUtils.isEmpty(ets[0].text.toString())) {
                item!!.delay = "0"
            } else {
                if(ets[0].text.toString().toLong() <= 12000) {
                    item!!.delay = ets[0].text.toString()
                }
            }
        }

        if (ets.size < 4 && !TextUtils.isEmpty(ets[0].text)&&ets[0].text.toString().toLong() > 12000) {
            Toll.toll("延时时间不能超过12s")
        } else {
            if (item!!.editor == 1) {

                var results = arrayOf(false,false,false,false)

                if (item.editorIndex == 0) {//检查编码
                    results[0] = checkUidCode(item)
                }

                if (item.editorIndex == 1) {//检查延时
                    results[1] = checkDelayTime(item)
                }

                if (item.editorIndex == 2) {//检查排号
                    results[2] = checkSortNumber(item)
                }

                if (item.editorIndex == 3) {//检查孔号
                    results[3] = checkHoleNumber(item)
                }

                if (item.editorIndex < ets.size) {
                    moveFocusableToIndex(item)
                    return
                }

                closeKeyBorad()

                if (checkSubmitInsert(results,item)) {
                    submitInsert(item)
                } else {
                    checkDataTotalDelay()
                }

            } else {
                closeKeyBorad()
                isEditor = false
                item.editor = 0
                notifyItemChanged(position)
                DBHelper.insertNewLeiGuanData(object :
                    ObservableUtil.Companion.OnNextCallback<Boolean>() {
                    override fun onNext(t: Boolean) {
                        mOnEditorCallback?.onEditorResult()
                    }
                }, *data.toTypedArray())
            }
        }
    }

    /**
     * 检查表单
     */
    private fun checkSubmitInsert(results:Array<Boolean>,item: LeiGuanEntity):Boolean {
        for((i,b) in results.withIndex()){
            if(!b){
                item.editorIndex = i
                return false
            }
        }
        return true
    }

    /**
     * 插入
     */
    private fun submitInsert(item: LeiGuanEntity) {
        val str = makeData(
            Integer.toBinaryString(Integer.parseInt(item.sort) - 1),
            6
        ) + makeData(Integer.toBinaryString(Integer.parseInt(item.kong) - 1), 10)
        val ten: Int = str.toInt(2)
        val hexString = Integer.toHexString(ten)
        item.holeNumber = hexString
        isEditor = false
        item.editor = 0
        item.collectorNumber = ""
        notifyItemChanged(position)
        DBHelper.insertNewLeiGuanData(object : ObservableUtil.Companion.OnNextCallback<Boolean>() {
            override fun onNext(t: Boolean) {
                mOnEditorCallback?.onEditorResult()
            }
        }, *data.toTypedArray())
    }


    /**
     * 检查采集器编号
     */
    private fun checkCollectorNumber(item: LeiGuanEntity): Boolean {
        if (TextUtils.isEmpty(ets[4].text.toString())) {
            Toll.toll("请输入采集器编号")
            return false
        }
        item.collectorNumber = ets[4].text.toString()
        item.editorIndex = 5
        return true
    }


    /**
     * 检查孔号
     */
    private fun checkHoleNumber(item: LeiGuanEntity): Boolean {

        if (TextUtils.isEmpty(ets[3].text.toString())) {
            Toll.toll("请输入孔号")
            return false
        }

        item.kong = ets[3].text.toString().toLong().toString()

        if (TextUtils.isEmpty(item.kong)) {
            Toll.toll("请输入孔号")
            return false
        }

        if (TextUtils.equals("0", item.kong)) {
            Toll.toll("孔号不能为0")
            return false
        }

        item.editorIndex = 4
        return true
    }

    /**
     * 检查排号
     */
    private fun checkSortNumber(item: LeiGuanEntity): Boolean {

        if (TextUtils.isEmpty(ets[2].text.toString())) {
            Toll.toll("请输入排号")
            return false
        }

        item.sort = ets[2].text.toString().toLong().toString()

        if (TextUtils.isEmpty(item.sort)) {
            Toll.toll("请输入排号")
            return false
        }

        if (TextUtils.equals("0", item.sort)) {
            Toll.toll("排号不能为0")
            return false
        }

        item.editorIndex = 3
        return true
    }

    /**
     * 检查延时
     */
    private fun checkDelayTime(item: LeiGuanEntity): Boolean {
        if (TextUtils.isEmpty(ets[1].text.toString())) {
            Toll.toll("请输入延时")
            return false
        }

        if (ets[1].text.toString().toLong() < 0) {
            Toll.toll("请输入正确的延时")
            return false
        }

        item.delay = ets[1].text.toString().toLong().toString()

        if (item.delay.toLong() > 12000) {
            Toll.toll("延时时间不能超过12s")
            return false
        }

        item.editorIndex = 2
        return true
    }

    /**
     * 检查编码
     */
    private fun checkUidCode(item: LeiGuanEntity): Boolean {
        if (TextUtils.isEmpty(ets[0].text.toString())) {
            Toll.toll("请输入编码")
            return false
        }
        if (ets[0].text.toString().length == 13) {
            val bindEditorData = bindEditorData(item)
            if (!bindEditorData) {
                return false
            }
        } else {
            Toll.toll("请输入正确的编码")
            return false
        }
        item.editorIndex = 1
        return true
    }


    /**
     * 检查编码是否重复
     */
    private fun checkUidRepeat(uid: String): Boolean {
        var i = 0
        data.forEach {
            if (TextUtils.equals(uid, it.UID) && i != position) {
                Toll.toll("该编码已存在")
                return true
            }
            i++
        }
        return false
    }

    private fun closeKeyBorad() {
        ets.forEach {
            KeyBoardUtil.hideSoftInput(it)
        }
    }


    fun isEditor(): Boolean {
        return isEditor
    }

    /**
     * 插入
     */
    private fun convertInsertDelay(helper: BaseViewHolder, item: LeiGuanEntity) {
        if (position >= 0) {
            if (this.widths.isNotEmpty()) {
                setViewWidth(
                    helper.getView(R.id.insertDelayItemNumberText)
                    , helper.getView(R.id.insertDelayItemCodeText)
                    , helper.getView(R.id.insertDelayItemTimeText)
                    , helper.getView(R.id.insertDelayItemSortText)
                    , helper.getView(R.id.insertDelayItemKongText)
                    , helper.getView(R.id.insertDelayItemCjqText)
                )

                setViewWidth(
                    helper.getView(R.id.insertDelayItemNumberText)
                    , helper.getView(R.id.insertDelayItemCodeTextView)
                    , helper.getView(R.id.insertDelayItemTimeTextView)
                    , helper.getView(R.id.insertDelayItemSortTextView)
                    , helper.getView(R.id.insertDelayItemKongTextView)
                    , helper.getView(R.id.insertDelayItemCjqText)
                )
            }

            release()

            isEditor = true
            val codeEt = helper.getView<SkinKeyEventEditorText>(R.id.insertDelayItemCodeText)
            val timeEt = helper.getView<SkinKeyEventEditorText>(R.id.insertDelayItemTimeText)
            val sortEt = helper.getView<SkinKeyEventEditorText>(R.id.insertDelayItemSortText)
            val kongEt = helper.getView<SkinKeyEventEditorText>(R.id.insertDelayItemKongText)
            //val cjqEt = helper.getView<SkinKeyEventEditorText>(R.id.insertDelayItemCjqText)

            texts.add(helper.getView(R.id.insertDelayItemCodeTextView))
            texts.add(helper.getView(R.id.insertDelayItemTimeTextView))
            texts.add(helper.getView(R.id.insertDelayItemSortTextView))
            texts.add(helper.getView(R.id.insertDelayItemKongTextView))

            codeEt.setOnKeyDownEventCallback(mOnKeyDownEventCallback)
            timeEt.setOnKeyDownEventCallback(mOnKeyDownEventCallback)
            sortEt.setOnKeyDownEventCallback(mOnKeyDownEventCallback)
            kongEt.setOnKeyDownEventCallback(mOnKeyDownEventCallback)
            //cjqEt.setOnKeyDownEventCallback(mOnKeyDownEventCallback)

            convertInsertDelayData(helper, item)

            helper.setText(R.id.insertDelayItemNumberText, (position + 1).toString())

            ets.add(codeEt)
            ets.add(timeEt)
            ets.add(sortEt)
            ets.add(kongEt)

            changeEditorFocus(0)

            addTextChangedWatcher(timeEt, sortEt, kongEt)

            addFocusableCallback(item)

        }
    }


    /**
     * 添加输入回调
     */
    private fun addTextChangedWatcher(timeEt:SkinKeyEventEditorText,sortEt:SkinKeyEventEditorText,kongEt:SkinKeyEventEditorText){
        timeEt.addTextChangedListener(object : TextWatcher{
            override fun afterTextChanged(s: Editable?) {
                if(s != null && s!!.isNotEmpty()){
                    val time = s.toString().toInt()
                    if(time > 12000){
                        timeEt.setText("12000")
                    } else if(time == 0 && s.length>1){
                        timeEt.setText("0")
                    } else if(s.length > 1&&s.startsWith("0")){
                        timeEt.setText(s.delete(0,1))
                    }
                }
            }

            override fun beforeTextChanged(
                s: CharSequence?,
                start: Int,
                count: Int,
                after: Int
            ) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }
        })

        sortEt.addTextChangedListener(object : TextWatcher{
            override fun afterTextChanged(s: Editable?) {
                if(s != null && s!!.isNotEmpty()){
                    val sort = s.toString().toInt()
                    if(sort == 0){
                        sortEt.setText("")
                    }
                }
            }

            override fun beforeTextChanged(
                s: CharSequence?,
                start: Int,
                count: Int,
                after: Int
            ) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }
        })

        kongEt.addTextChangedListener(object : TextWatcher{
            override fun afterTextChanged(s: Editable?) {
                if(s != null && s!!.isNotEmpty()){
                    val kong = s.toString().toInt()
                    if(kong == 0){
                        kongEt.setText("")
                    }
                }
            }

            override fun beforeTextChanged(
                s: CharSequence?,
                start: Int,
                count: Int,
                after: Int
            ) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }
        })
    }

    var mOnKeyDownEventCallback = object : SkinKeyEventEditorText.Companion.OnKeyDownEventCallback {
        override fun onKeyDownEvent(keyCode: Int, event: KeyEvent?): Boolean {
            return onKeyDown(keyCode, event)
        }
    }


    /**
     * 组装区排孔数据
     */
    private fun makeData(str: String, length: Int): String? {
        var s = ""
        val strLength = length - str.length
        for (i in 0 until strLength) {
            s += "0"
        }
        return s + str
    }

    /**
     * 显示插入数据
     */
    private fun convertInsertDelayData(helper: BaseViewHolder, item: LeiGuanEntity) {
        super.convert(helper, item)
        item.run {
            helper.setText(R.id.insertDelayItemNumberText, (helper.adapterPosition + 1).toString())
            helper.setText(R.id.insertDelayItemCodeText, StringUtils.getUid(UID))
            helper.setText(R.id.insertDelayItemTimeText, delay)

            helper.setText(R.id.insertDelayItemCodeTextView, StringUtils.getUid(UID))
            helper.setText(R.id.insertDelayItemTimeTextView, delay)

            if (!TextUtils.isEmpty(holeNumber)) {
                val hexString: String = StringUtils.HexToBin16(holeNumber)
                helper.setText(
                    R.id.insertDelayItemSortText,
                    StringUtils.getRowNumber(hexString).toString()
                )
                helper.setText(
                    R.id.insertDelayItemKongText,
                    StringUtils.getHoleNumber(hexString).toString()
                )

                helper.setText(
                    R.id.insertDelayItemSortTextView,
                    StringUtils.getRowNumber(hexString).toString()
                )
                helper.setText(
                    R.id.insertDelayItemKongTextView,
                    StringUtils.getHoleNumber(hexString).toString()
                )
                helper.setText(R.id.insertDelayItemCjqText, collectorNumber)
            } else {
                if (!TextUtils.isEmpty(sort)) {
                    helper.setText(R.id.insertDelayItemSortText, sort)
                    helper.setText(R.id.insertDelayItemSortTextView, sort)
                } else {
                    helper.setText(R.id.insertDelayItemSortText, "")
                    helper.setText(R.id.insertDelayItemSortTextView, "")
                }
                if (!TextUtils.isEmpty(kong)) {
                    helper.setText(R.id.insertDelayItemKongText, kong)
                    helper.setText(R.id.insertDelayItemKongTextView, kong)
                } else {
                    helper.setText(R.id.insertDelayItemKongText, "")
                    helper.setText(R.id.insertDelayItemKongTextView, "")
                }
                helper.setText(R.id.insertDelayItemCjqText, collectorNumber)
            }

        }
    }


    /**
     * 焦点变化
     */
    private fun moveFocusableToIndex(item: LeiGuanEntity) {
        if (item.editorIndex < ets.size) {
           changeEditorFocus(item.editorIndex)
        }
    }

    /**
     * 添加聚焦回调
     */
    private fun addFocusableCallback(item: LeiGuanEntity) {
        if (item.editorIndex < ets.size) {
            for ((i, et) in texts.withIndex()) {
                et.setOnClickListener {
                    item.editorIndex = i
                    changeEditorFocus(i)                }
            }
        }
    }

    /**
     * 改变焦点
     */
    private fun changeEditorFocus(index:Int){
        for ((i, et) in ets.withIndex()) {
            if (i == index) {
                et.visibility = View.VISIBLE
                texts[i].visibility = View.GONE
                et.requestFocus()
                et.isCursorVisible = true
            } else {
                et.isCursorVisible = false
                et.visibility = View.GONE
                et.clearFocus()
                texts[i].visibility = View.VISIBLE
                texts[i].text = et.text
            }
        }
    }

    /**
     * 延时修改
     */
    private fun convertUpdateDelay(helper: BaseViewHolder, item: LeiGuanEntity) {
        release()
        if (this.widths.isNotEmpty()) {
            setViewWidth(
                helper.getView(R.id.updateDelayNumberText)
                , helper.getView(R.id.updateDelayCodeText)
                , helper.getView(R.id.updateDelayTimeText)
                , helper.getView(R.id.updateDelaySortText)
                , helper.getView(R.id.updateDelayKongText)
                , helper.getView(R.id.updateDelayCjqText)
            )
        }

        item.run {
            isEditor = true
            val editText = helper.getView<SkinKeyEventEditorText>(R.id.updateDelayTimeText)
            editText.setOnKeyDownEventCallback(mOnKeyDownEventCallback)
            editText.addTextChangedListener(object : TextWatcher{
                override fun afterTextChanged(s: Editable?) {
                    if(s != null && s!!.isNotEmpty()){
                        val time = s.toString().toInt()
                        if(time > 12000){
                            editText.setText("12000")
                        }
                    }
                }

                override fun beforeTextChanged(
                    s: CharSequence?,
                    start: Int,
                    count: Int,
                    after: Int
                ) {

                }

                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

                }
            })
            ets.add(editText)
            helper.setText(R.id.updateDelayNumberText, (helper.adapterPosition + 1).toString())
            helper.setText(R.id.updateDelayCodeText, StringUtils.getUid(UID))
            helper.setText(R.id.updateDelayTimeText, delay)
            if (!TextUtils.isEmpty(holeNumber)) {
                val hexString: String = StringUtils.HexToBin16(holeNumber)
                helper.setText(
                    R.id.updateDelaySortText,
                    StringUtils.getRowNumber(hexString).toString()
                )
                helper.setText(
                    R.id.updateDelayKongText,
                    StringUtils.getHoleNumber(hexString).toString()
                )
                helper.setText(R.id.updateDelayCjqText, collectorNumber)
            } else {
                helper.setText(R.id.updateDelaySortText, "0")
                helper.setText(R.id.updateDelayKongText, "0")
                helper.setText(R.id.updateDelayCjqText, "0")
            }

            editText.isFocusable = true
            editText.requestFocus()
        }
    }

    fun release() {
        ets.clear()
        texts.clear()
    }

    interface OnEditorCallback {
        fun onEditorResult()
    }
}